/*新增费用*/
import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image, TouchableOpacity, FlatList
} from "react-native";
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { API, API_GENERATE } from '../../../../config/api';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { Common } from '../../../../component/common/Common.js'
import HTTP from '../../../../utils/http';
import { CURRENCY } from '../../../../utils/helper';

const scale = GLOBAL.SCALE;
let orderId = '';
let prodItem = {};
const sellPic = require('../../../../imgs/apply/sellXin.png');//销
const shoppPic = require('../../../../imgs/apply/shopp.png');//购

export class ReportListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { params } = navigation.state;
		let titleName = '选择' + (params.orderType == 'P' ? '销售' : '采购') + '成交报告'
		return {
			headerTitle: titleName,
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};
	constructor(props) {
		super(props);
		let { params } = props.navigation.state;
		orderId = params.orderId;
		prodItem = params.prodItem;
		this.state = {
			reportList: [],
			selectedItems: prodItem.orderMappingList || [],
			pageNo: 1,
			pageSize: 10,
			loadIcon: false,
			orderId: orderId,
			orderType: params.orderType,
			pageStatus: {
				status: 'loading'
			}
		}

	}

	componentWillMount () {
		this._getReportList()
	}

	//获取成交报告单
	async _getReportList (reportData) {
		this.setState({ loadIcon: true })
		let { pageNo, pageSize } = this.state;
		let orderType = this.state.orderType == 'P' ? 'S' : 'P';

		let respData = await HTTP.POST(API_GENERATE(API.ORDER_CAN_MAP_LIST), { goodsId: prodItem.goodsId, orderId: prodItem.orderId, pageNo, pageSize })

		if (respData && respData.rows.length > 0) {
			let reportList = respData.rows || [];
			let { selectedItems } = this.state;

			let attrName = this.state.orderType === 'P' ? 'salesOrderItemId' : 'purchaseOrderItemId';
			reportList.map((rItem, rIndex) => {
				rItem.isM = false;
				selectedItems.map((oItem, oIndex) => {
					//已填写的数量
					oItem.paramsQ = oItem.quantity;
					if (rItem.itemId === oItem[attrName]) {
						//已填写的数量
						rItem.paramsQ = oItem.quantity;
						rItem.isM = true;
					}
				})
			})

			if (reportData && reportData.length > 0) {
				reportList = [...reportData, ...reportList];
			}
			this.setState({
				reportList: reportList,
				lastPage: respData.lastPage,
				selectedItems: selectedItems,
				pageStatus: {
					status: 'data',
				}
			});
		} else {
			this.setState({
				pageStatus: {
					status: 'empty',
					emptyText: '没有可关联成交报告呢~',
					// onEmptyPress: () => { this.props.navigation.goBack() }
				}
			});
		}
		this.setState({ loadIcon: false })
	}

	//选择关联 orderItemList
	_selectOrder = (item, sIndex) => {
		let { selectedItems, reportList } = this.state;
		let ifSelected = false;
		let unCheckedIndex;
		let attrName = this.state.orderType === 'P' ? 'salesOrderItemId' : 'purchaseOrderItemId';
		selectedItems.map((selectItem, index) => {
			if (selectItem[attrName] === item.itemId) {
				ifSelected = true;
				unCheckedIndex = index;
				return;
			}
		})
		if (ifSelected) {
			selectedItems.splice(unCheckedIndex, 1);
			reportList[sIndex].isM = false;
		} else {
			selectedItems.push(item);
			reportList[sIndex].isM = true;
		}
		this.setState({ selectedItems, reportList });
	}

	//保存 orderItemList下的orderItemMappingInfo
	async _confirm () {
		let { selectedItems } = this.state;
		prodItem.orderMappingList = selectedItems;
		this.props.navigation.state.params.callBack(prodItem);
		this.props.navigation.goBack();
	}

	//下拉刷新
	_isLoadRefresh = () => {
		this.setState({ pageNo: 1 }, () => {
			this._getReportList();
		});

	}

	//上拉加载
	_loadData = () => {
		let { pageNo, lastPage, reportList } = this.state
		if (pageNo > lastPage || pageNo == lastPage) return;
		pageNo += 1;
		this.setState({ pageNo }, () => {
			this._getReportList(reportList);
		})
	}

	_renderItem = (data) => {
		let { item, index } = data;
		return (<TouchableOpacity key={index} style={styles.itemBox} onPress={() => {
			this._selectOrder(item, index)
		}}>
			<View style={styles.rightItem}>
				<View style={{
					flexDirection: 'row',
					alignItems: 'center',
				}}>
					<Image source={item.orderType && item.orderType == 'P' ? shoppPic : sellPic} />
					<Text style={styles.companyName}>{item.companyName}</Text>
				</View>
				<Text style={styles.text}>订单编号：{item.orderId}</Text>
				<Text style={styles.text}>{item.goodsName}：{item.quantity + item.uomName}</Text>
				<Text style={styles.text}>未匹配数量：{item.noMappingQuantity + item.uomName}</Text>
				<Text style={styles.text}>单价：{item.price || 0}{CURRENCY.getUnit(item.currency).text}</Text>
				<Text style={styles.text}>出库地点：{item.deliveryAddressName}{item.isM}</Text>
			</View>
			{item.isM ?
				<Image style={styles.iconImg} source={require('../../../../imgs/global/success.png')} /> :
				<Image style={styles.iconImg} source={require('../../../../imgs/global/option.png')} />}
		</TouchableOpacity>)
	}

	render () {
		let { reportList, pageStatus } = this.state;
		return (
			<View style={styles.container} >
				{
					reportList && reportList.length > 0 ?
						<View style={styles.container}>
							{/* <View style={{
								flexDirection: 'row', alignItems: 'center', borderBottomColor: style.color.border,
								borderBottomWidth: 1,
							}}>
								<Text style={styles.searchType}>仓库区域</Text>
								<Text style={styles.searchType}>交货期限</Text>
							</View> */}

							<FlatList
								data={reportList}
								renderItem={(data) => { return this._renderItem(data) }}
								refreshing={this.state.loadIcon}
								onRefresh={() => { this._isLoadRefresh() }}
								onEndReachedThreshold={1}
								onEndReached={() => { this._loadData() }} />
							<View style={{ width: '100%', height: 60 * scale, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
								<TouchableOpacity onPress={() => { this._confirm() }} style={[styles.btnSave, styles.mtp9]}>
									<Text style={styles.btnSaveText}>确定</Text>
								</TouchableOpacity>
							</View>
						</View>
						: <PageStatusIndex {...pageStatus} />
				}
			</View >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white,
	},
	searchType: {
		width: 187 * scale,
		height: 45 * scale,
		lineHeight: 45 * scale,
		fontSize: 14 * scale,
		color: style.color.normal,
		textAlign: 'center'
	},
	itemBox: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 15 * scale,
		paddingRight: 12 * scale,
		borderBottomColor: style.color.border,
		borderBottomWidth: 1,
	},
	leftItem: {
		width: 78 * scale,
		height: 20 * scale
	},
	rightItem: {
		paddingTop: 12 * scale,
		paddingBottom: 12 * scale,
		paddingLeft: 16 * scale,
		flex: 1,
	},
	iconImg: {
		width: 14 * scale,
		height: 14 * scale,
	},
	companyName: {
		fontSize: 14 * scale,
		color: style.color.normal,
		paddingLeft: 8 * scale,
	},
	text: {
		fontSize: 12 * scale,
		color: style.color.darkGray,
		paddingTop: 6 * scale,
	},
	SaveText: {
		color: style.color.white,
		fontSize: 18 * scale,
		lineHeight: 44 * scale,
		textAlign: 'center',
	},
	btnSave: {
		width: 345 * scale,
		height: 44 * scale,
		backgroundColor: style.color.themeColor,
		borderRadius: 22 * scale,
		position: 'absolute',
		bottom: 0
	},
	mtp9: {
		marginTop: 9 * scale,
		marginBottom: 9 * scale
	},
	statusStyle: {
		flex: 1,
		position: 'absolute',
		height: '100%',
		width: '100%',
		top: 0,
		left: 0,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center'
	},
	btnSaveText: {
		color: style.color.white,
		fontSize: 18 * scale,
		lineHeight: 44 * scale,
		textAlign: 'center',
	},
})
